<?php

class Helper_Formatter
{
    static function format($source, $formatter)
    {
        switch ($formatter)
        {
        case 'markdown':
            return self::formattingByMarkdown($source);
            break;
        case 'texy':
            return self::formattingByTexy($source);
            break;
        default:
            return nl2br(h($source));
        }
    }

    static function formattingByMarkdown($source)
    {
        if (!function_exists('Markdown'))
        {
            require_once Q::ini('app_config/ROOT_DIR') . '/lib/markdown/markdown.php';
        }

        return Markdown($source);
    }

    static function formattingByTexy($source)
    {
        static $texy;

        if (is_null($parser))
        {
            if (!class_exists('Texy', false))
            {
                $dir = Q::ini('app_config/ROOT_DIR') . '/lib';
                require_once "{$dir}/geshi/geshi.php";
                require_once "{$dir}/texy/texy.php";
            }

            $texy = new Texy();
            $texy->addHandler('block', array(__CLASS__, 'texyBlockHandler'));
        }

        return $texy->process($source);
    }

    static function texyBlockHandler($invocation, $blocktype, $content, $lang, $modifier)
    {
        if ($blocktype !== 'block/code')
        {
            return $invocation->proceed();
        }

        $texy = $invocation->getTexy();

        if ($lang == 'html') $lang = 'html4strict';
        $content = Texy::outdent($content);
        $geshi = new GeSHi($content, $lang);

        // GeSHi could not find the language
        if ($geshi->error)
        {
            return $invocation->proceed();
        }

        // do syntax-highlighting
        $geshi->set_encoding('UTF-8');
        $geshi->set_header_type(GESHI_HEADER_PRE);
        $geshi->enable_classes();
        $geshi->enable_keyword_links(false);
        $geshi->set_overall_style('');
        $geshi->set_overall_class('code');

        // save generated stylesheet
        $content = $geshi->parse_code();

        // check buggy GESHI, it sometimes produce not UTF-8 valid code :-((
        $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);

        // protect output is in HTML
        $content = $texy->protect($content, Texy::CONTENT_BLOCK);

        $el = TexyHtml::el();
        $el->setText($content);
        return $el;
    }

}

